<template>
    <div>
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>文件导入</span>
                </div>
            </template>
            <div>
                <div>
                    <el-upload class="upload-demo" :on-change="changeFile" :auto-upload="false">
                        <el-button type="primary">点击上传</el-button>
                    </el-upload>
                </div>
                <div>
                    <el-table :data="tableData">
                        <el-table-column type="index" label="序号" width="120px" />
                        <el-table-column prop="id" label="id"></el-table-column>
                        <el-table-column prop="name" label="姓名"></el-table-column>
                        <el-table-column prop="date" label="日期"></el-table-column>
                        <el-table-column prop="address" label="住址"></el-table-column>
                    </el-table>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import * as xlsx from 'xlsx'
import type { UploadFile } from 'element-plus'
import { shallowRef } from 'vue';

type ExItem = {
    id: string
    name: string
    date: string
    address: string
}

let tableData = shallowRef<Array<ExItem>>()

let changeFile = (uploadFile: UploadFile) => {
    //1 获取文件信息
    const file = uploadFile.raw
    console.log(file);

    //2 创建读取器
    const fileReader = new FileReader()
    //3 读取文件为二进制内容
    fileReader.readAsBinaryString(file!)

    //4 监听读取完成 进行excel操作
    fileReader.onload = (ev: any) => {
        //获取二进制数据
        const data = ev.target.result
        //读取二进制 生成工作簿
        const workbook = xlsx.read(data, {
            type: 'binary',
        })
        //获取表名
        const sheetName = workbook.SheetNames[0]
        //获取工作表 转为json格式
        const worksheet = workbook.Sheets[sheetName]
        //转为json格式
        const excelJsonData = xlsx.utils.sheet_to_json(worksheet)
        //数据赋值
        tableData.value = excelJsonData as any

        tableData.value = tableData.value?.map((v: any) => {
            return {
                id: v.id,
                name: v.名称,
                address: v.地址,
                date: v.时间,
            }
        })

    }
}
</script>

<style scoped></style>